package fastHttp

import (
	"encoding/json"
	"github.com/valyala/fasthttp"
)

type FastHttp struct {
}

func New() (fastHttp *FastHttp) {
	fastHttp = new(FastHttp)
	return fastHttp
}
func (f FastHttp) Get(url string) ([]byte, error) {
	req := &fasthttp.Request{}
	req.SetRequestURI(url)
	requestBody := []byte(`{}`)
	req.SetBody(requestBody)
	// 默认是application/x-www-form-urlencoded
	req.Header.SetContentType("application/json")
	req.Header.SetMethod("GET")
	resp := &fasthttp.Response{}
	client := &fasthttp.Client{}
	if err := client.Do(req, resp); err != nil {
		return nil, err
	}
	return resp.Body(), nil
}

func (f FastHttp) PostJsonData(url string, param map[string]interface{}) ([]byte, error) {
	req := &fasthttp.Request{}
	req.SetRequestURI(url)
	req.Header.SetContentType("application/json")
	req.Header.SetMethod("POST")
	substring, _ := json.Marshal(param)
	req.SetBody(substring)
	resp := &fasthttp.Response{}
	client := &fasthttp.Client{}
	if err := client.Do(req, resp); err != nil {
		return nil, err
	}
	return resp.Body(), nil
}
func (f FastHttp) GetString(url string) string {
	re, err := f.Get(url)
	if err != nil {
		return ""
	}
	return string(re)
}
func (f FastHttp) PostJsonDataString(url string, param map[string]interface{}) string {
	re, err := f.PostJsonData(url, param)
	if err != nil {
		return ""
	}
	return string(re)
}
func (f FastHttp) PostStringDataString(url string, param string) string {

	return string(f.PostStringDataByte(url, param))
}
func (f FastHttp) PostStringDataByte(url string, param string) []byte {
	req := &fasthttp.Request{}
	req.SetRequestURI(url)
	req.Header.SetContentType("application/json")
	req.Header.SetMethod("POST")
	req.SetBody([]byte(param))
	resp := &fasthttp.Response{}
	client := &fasthttp.Client{}
	if err := client.Do(req, resp); err != nil {
		return []byte("")
	}
	return resp.Body()
}
